<?php

namespace app\admin\service;

use app\common\logic\CouponLogic;
use app\common\model\commonModel;
use app\common\model\trCache;
use app\common\model\trCoupon;
use app\common\util\ErrorCode;

/**
 * Class Auth
 * @package app\admin\service
 * 优惠券服务类
 */
class CouponService
{
    private $field = [
        "type" => "require", "name" => "require", "condition" => 'require', "content" => '', "amount" => "require", "mold" => "require",
        "time_from" => "require", "time_to" => "time_from"
    ]; //填入数据库需要存储的表字段
    private $data = [];
    private $returnData;
    private $mall_id = 0;
    private $params;

    public function __construct($data, $params = [])
    {
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    // 获取优惠券数据的分页列表
    public function getList(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        $filter = array(["mall_id", "=", $this->mall_id]);
        if(!empty($this->params['search'])){
            $filter[] = ['name', 'like', "{$this->params["search"]}%"];
        }
        if(!empty($this->params['type'])){
            $filter[] = ['type', '=', $this->params["type"]];
        }
        if(isset($this->params['status'])){
            $filter[] = ['status', '=', $this->params["status"]];
        }
        if (isset($this->params['mold'])){
            $filter[] = ['mold', '=', $this->params["mold"]];
        }
        $model = new trCoupon();
        $data = $model->getList("*", $filter, $page, $pageSize);
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    // 添加优惠券
    public function toAdd(){
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if($v === 'require' && !isset($this->params[$ks])){
                return ErrorCode::code("params_not_exist", $ks);
            }
            $this->data[$k] = isset($this->params[$ks]) ? $this->params[$ks] : $v;
        }
        if(empty(trCache::getValue("value", ["key" => "addCoupon_".md5(json_encode($this->data))]))) {
            if ($this->data["condition"] == "2" && floatval($this->data["content"]) < $this->data["amount"]) { // 使用条件：订单金额满足
                return ErrorCode::code("customized", "优惠金额不能大于订单金额");
            }
            $model = new trCoupon();
            $result = $model->add($this->data, true);
            if (isset($result["code"])) {
                return $result;
            }
            if (!$result) {
                $this->returnData = ErrorCode::$errorCode["fail"];
            } else {
                trCache::saveCache(["key" => "addCoupon_" . md5(json_encode($this->data)), "value" => 1, "time" => 10]);
                $this->data['id'] = $result;
                $this->data['status'] = 1;
                if (!$this->onlyOpenStatus($this->data)) {
                    return ErrorCode::code("customized", "优惠券添加成功，但是修改其它优惠券状态失败");
                }
                if (!CouponLogic::addUserCouponByTemplate($result)) {
                    return ErrorCode::code("customized", "发放优惠券到用户失败，请重新添加");
                }
            }
        }
        return $this->returnData;
    }

    // 更新优惠券
    public function toUpdate(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }

        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if($v === 'require' && !isset($this->params[$ks])){
                return ErrorCode::code("params_not_exist", $ks);
            }
            if(isset($this->params[$ks])){
                $this->data[$k] = $this->params[$ks];
            }
        }
        if ($this->data["condition"] == "2" && floatval($this->data["content"]) < $this->data["amount"]) { // 使用条件：订单金额满足
            return ErrorCode::code("customized", "优惠金额不能大于订单金额");
        }
        $model = new trCoupon();
        $result = $model->doUpdate($this->data, ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(isset($result["code"])) {
            return $result;
        }
        if(!$result){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        return $this->returnData;
    }

    // 优惠券的详细内容
    public function getDetail(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $model = new trCoupon();
        $data = $model->getFields("*", ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if($data["condition"] == "3"){
            $data["content"] = explode(",", $data["content"]);
        }
        $this->returnData["data"] = $data;
        return $this->returnData;
    }

    // 更新状态
    public function toUpdateStatus(){ //状态：1启用，0弃用
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        if(!isset($this->params["status"])){
            return ErrorCode::code("params_not_exist", "status");
        }
        if(!in_array($this->params["status"], [1,0])){
            return ErrorCode::code("params_error", "status(1启用，0弃用)");
        }
        $this->data["status"] = $this->params["status"];
        $model = new trCoupon();
        $result = $model->doUpdate($this->data, ["id" => $this->params["id"], "mall_id" => $this->mall_id]);
        if(isset($result["code"])) {
            return $result;
        }
        if(!$result){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        if (!$this->onlyOpenStatus($this->params)){
            return ErrorCode::code("customized", "优惠券更新成功，但是修改其它优惠券状态失败");
        }
        return $this->returnData;
    }

    // 删除优惠券
    public function toDel(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $model = new trCoupon();
        $result = $model->delById($this->params['id']);
        if (isset($result["code"])) {
            return $result;
        }
        if (!$result) {
            $this->returnData = ErrorCode::$errorCode['fail'];
            $this->returnData["msg"] = "删除失败";
        }
        commonModel::delByFilter(userCouponTable, ["coupon_id" => $this->params["id"], "mall_id" => $this->mall_id]);
        return $this->returnData;
    }

    //推荐、被推荐优惠券保持唯一开启状态
    public function onlyOpenStatus($data){
        $model = new trCoupon();
        if(!isset($data['mold'])) {
            $data = $model->getFields("status,id,mold", ["id" => $data["id"], "mall_id" => $this->mall_id]);
        }
        if ($data['mold'] != 1 && (int)$data['status'] == 1){
            $fields[] =  ['mold', '=', $data['mold']];
            $fields[] =  ['id', '<>', $data["id"]];
            $fields[] =  ['mall_id', '=', $this->mall_id];
            $result = $model->doUpdate(["status" => 0], $fields);
            if (!$result) {
                return false;
            }
        }
        return true;
    }
}